package com.pine.manager.config;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.pine.common.threadpool.ThreadPoolConfig;
import com.pine.common.threadpool.ThreadPoolConstant;
import com.pine.common.threadpool.core.DynamicThreadPoolManager;
import com.pine.common.threadpool.core.ThreadPoolConfigFactory;
import com.pine.dao.pineframework.entity.SysDict;
import com.pine.manager.core.StringPool;
import com.pine.manager.pineframework.SysDictItemManager;
import com.pine.manager.pineframework.SysDictManager;
import com.pine.manager.pineframework.bo.SysDictBo;
import com.pine.manager.pineframework.bo.SysDictItemBo;
import com.pine.manager.pineframework.query.SysDictItemQuery;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 * 动态线程池初始化配置信息
 *
 * @author pine manage
 * @since 2024-08-29
 */
@Slf4j
@Configuration
public class DynamicThreadPoolInitConfig {
    @Resource
    private SysDictManager sysDictManager;

    @Resource
    private SysDictItemManager sysDictItemManager;

    @PostConstruct
    private void init() {
        initThreadPoolConfig();
    }


    private void initThreadPoolConfig() {
        // 根据code查字典
        SysDictBo sysDictBo = sysDictManager.getOneByUniqueKey(StringPool.DYNAMIC_THREAD_POOL_CONFIG_DICT_CODE, SysDict::getCode);
        if (sysDictBo == null) {
            return;
        }

        // 查字典明细
        SysDictItemQuery sysDictItemQuery = new SysDictItemQuery();
        sysDictItemQuery.setDictId(sysDictBo.getId());
        List<SysDictItemBo> sysDictItemBos = sysDictItemManager.list(sysDictItemQuery);
        if (CollUtil.isNotEmpty(sysDictItemBos)) {
            for (SysDictItemBo sysDictItemBo : sysDictItemBos) {
                // 线程池配置key，例如：businessCode##businessKey
                String configKey = sysDictItemBo.getName();
                // 线程池配置json，例如：{"maximumPoolSize":10,"corePoolSize":5,"keepAliveTime":60,"keepAliveTimeUnit":"SECONDS","blockingQueueCapacity":1000,"rejectedPolicyCode":"DiscardPolicy"}
                String configValueJson = sysDictItemBo.getValue();

                String[] businessCodeAndKey = configKey.split(ThreadPoolConstant.THREAD_POOL_NAME_SEPARATOR);
                ThreadPoolConfig threadPoolConfig = JSONUtil.toBean(configValueJson, ThreadPoolConfig.class);
                // 增加线程池配置
                ThreadPoolConfigFactory.addThreadPoolConfig(businessCodeAndKey[0], businessCodeAndKey[1], threadPoolConfig);
                log.info("扫描到线程池(configKey={}##{})配置信息：{}",businessCodeAndKey[0], businessCodeAndKey[1], threadPoolConfig);
                // 创建线程池
                DynamicThreadPoolManager.getThreadPoolExecutor(businessCodeAndKey[0], businessCodeAndKey[1]);
                log.info("创建线程池(configKey={}##{})",businessCodeAndKey[0], businessCodeAndKey[1]);
            }
        }
    }
}
